package com.ruoyi.redisDemo;

import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/RedissonController")
public class RedissonTestController {
    @Autowired
    private RedissonClient redissonClient;

    /**
     *     定义一个锁 BOOK_KEY = "test:book:"
     */
    private final String  BOOK_KEY = "test:book:";

    /**
     * 定义修改图书的方法updateBook
     *  1.定义锁的密钥 lockKey
     *  2.获取一个读写锁
     *  3.创建锁并上锁 lock.writeLock()
     *  4.线程休眠模拟耗时5m操作
     *  5.最后释放锁 unlock
     */
    @GetMapping("/updateBook")
    public String updateBook(Long bookId){
        if (bookId == null || bookId<=0) {
            return "error";
        }
        String lockKey = BOOK_KEY+bookId;
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock(lockKey);
        RLock lock = readWriteLock.writeLock();
        try {
            lock.lock();
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

        return "ok";
    }

    /**
     * 定义获取图书的方法getBook
     * 1.定义锁的密钥 lockKey
     * 2.获取一个读写锁
     * 3.读到一个锁 lock.readLock()
     * 4. 锁上 模拟耗时操作  最后打开锁
     */
    @GetMapping("/getBook")
    public String getBook(Long bookId){
        String lockKey = BOOK_KEY + bookId;
        RReadWriteLock writeLock = redissonClient.getReadWriteLock(lockKey);
        RLock rLock = writeLock.readLock();
        try {
            rLock.lock();
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }

        return "ok";
    }
}
